__author__ = 'tyrion'

from Base import BaseCreateMonitors

from src.common.tools.salt import *
from  conf.gloal import *

from  src.common.tools.httpd import *


PLUGIN_NAME = "CreateTomcatMonitorPlugin.sh"
PLUGIN_CHILD_NAME = "acheck_port_tomcat"
targetPath = "/usr/lib/check_mk_agent/plugins/"


def GetInstanceDetailsFromConfigCenter( hostName):
        url = "http://%s/infrastructure-console/server/get/%s" % (CONFIG_CENTER_SERVER, hostName)
        print(url)
        Data = GetHttpRequest(url)
        print(Data)
        try:
            dicData = json.loads(Data[0])
        except IndexError:
            return "error"

        instanceDetail =" "
        portList = []
        for instance in dicData.get("instance"):
            name = instance.get("name")
            port = instance.get("custom").get("port")
            tmp = "{name}:{port} ".format(name = name, port = port)
            portList.append(tmp)
        # ports.join(port
        return  instanceDetail.join(portList)



class TomcatMonitors(BaseCreateMonitors):
    def __init__(self, conf):
        print("info: create tomcate Monitors init")
        self.hostName = conf.get("hostname", "error: not found host name")
        self.aliasName = conf.get("hostname", "error: not found host name")
        self.groupName = "flexweb"
        self.floder = "flexweb"
        self.ip = conf.get("ip", "error: not found host ip")
        self.ports = conf.get("ports", "error: not found host port")
        self.key = "%s%s" % (conf.get("place"), conf.get("env"))
        return


    def CreateMonitors(self):
        print("info: create tomcat monitors")
        print(self.key)
        print(REAL_SALT_MATER.get(self.key))

        #get plugin from file server
        getPluginCmd = "wget http://%s%s%s" %(FILE_SERVER, TOMCAT_PLUGIN_PATH, PLUGIN_NAME)
        getRet = ExecuteCommand(self.ip, getPluginCmd, saltMaster = REAL_SALT_MATER.get(self.key))

        getStatus = AnalyseResult(getRet, "wget plugin from file server failed", self.ip)
        if getStatus == "false":
            return False


        changeModeCmd = "chmod 777 /%s" %( PLUGIN_NAME)
        changeModeCmdRet  = ExecuteCommand(self.ip, changeModeCmd, saltMaster = REAL_SALT_MATER.get(self.key))
        changeModeErrMsg = "change  file mod failed"
        changeStatus = AnalyseResult(changeModeCmdRet, changeModeErrMsg, self.ip)
        if changeStatus == "false":
            return

        InstanceConf = GetInstanceDetailsFromConfigCenter(self.hostName)
        if InstanceConf == "error":
            return False

        #execute plugin
        # execPluginCmd = "%s%s  \"%s\"" % (targetPath, PLUGIN_NAME, self.ports)
        execPluginCmd = "/%s  \"%s\" " %(PLUGIN_NAME, InstanceConf)
        execPluginRet = ExecuteCommand(self.ip, execPluginCmd, saltMaster = REAL_SALT_MATER.get(self.key))
        execPluginErrMsg = "execute plugin %s failed" %(PLUGIN_NAME)
        execStatus = AnalyseResult(execPluginRet, execPluginErrMsg, self.ip)
        if execStatus == "false":
            return False

        #remove plugin
        # rmRet = ExecuteCommand(self.ip, ("rm -rf  %s%s*" %(targetPath, PLUGIN_NAME)))
        rmRet = ExecuteCommand(self.ip, ("rm -rf  /%s*" %( PLUGIN_NAME)), saltMaster = REAL_SALT_MATER.get(self.key) )
        rmErrorMsg = "rm file %s%s  failed" %(targetPath, PLUGIN_NAME)
        rmStatus = AnalyseResult(rmRet, rmErrorMsg, self.ip)
        if rmStatus == "false":
            return False

        # mv plugin to target dir
        mvRet = ExecuteCommand(self.ip, ("mv /%s  %s"% ( PLUGIN_CHILD_NAME, targetPath)),  saltMaster = REAL_SALT_MATER.get(self.key))
        mvErrorMsg = "mv plugin failed"
        mvStatus = AnalyseResult(mvRet, mvErrorMsg, self.ip)
        if mvStatus == "false":
            return False



    def AddToMonitorSvr(self):
        print("info: add tomcat monitors to monitor svr")
        cmdI = "cmk -I %s " %(self.hostName)
        cmdIRet = ExecuteCommand(REAL_ICINGA_SERVER.get(self.key),  cmdI, saltMaster = REAL_SALT_MATER.get(self.key))
        cmdIErrMsg = "cmk -I failed"
        cmdIStatus = AnalyseResult(cmdIRet, cmdIErrMsg, ICINGA_SERVER)
        if cmdIStatus == "false":
            return

        cmdO = "cmk -O"
        cmdORet = ExecuteCommand(REAL_ICINGA_SERVER.get(self.key), cmdO, saltMaster = REAL_SALT_MATER.get(self.key) )
        cmdOErrMsg = "cmk - O failed"
        cmdOStatus = AnalyseResult(cmdORet, cmdOErrMsg, REAL_ICINGA_SERVER.get(self.key))
        if cmdOStatus == "false":
            return

        # it is ok
        return  200

    def CreateMachine(self):

        print("info: tomcat create machine")
        url = '''
                http://%s:%s/check_mk/wato.py?filled_in=edithost&_username=icinga_nd&_secret=1234567890&_transid=-1&host=%s&_change_contactgroups=on&contactgroups_%s=on&contactgroups_use=on&_change_alias=on&attr_alias=%s&_change_ipaddress=on&attr_ipaddress=%s&attr_snmp_community=&attr_display_snmp_community=0&parents_0=&attr_tag_agent=cmk-agent|tcp&_change_tag_criticality=on&attr_tag_criticality=prod&_change_tag_networking=on&attr_tag_networking=lan&services=Save%%20%%26%%20go%%20to%%20Services&folder=%s&mode=newhost
                ''' % (REAL_ICINGA_SERVER.get(self.key), REAL_ICINGA_SERVER_PORT.get(self.key), self.hostName, self.groupName, self.aliasName, self.ip, self.floder)

        print( url)
        ret = GetHttpRequest(url)
        # uri = "http://%s/check_mk/wato.py" %(ICINGA_SERVER)
        # para = {"filled_in": "edithost", "_username": "icinga_nd", "_secret": "1234567890", "_transid": -1, "host": self.hostName, \
        #         "_change_contactgroups": "on", "contactgroups_%s"%(self.groupName): "on", "contactgroups_use": "on", "_change_alias": "on",\
        #         "attr_alias": self.aliasName, "_change_ipaddress": "on", "attr_ipaddress": self.ip, "attr_snmp_community": "",\
        #         "attr_display_snmp_community": 0, "parents_0": "", "attr_tag_agent": "cmk-agent|tcp", "_change_tag_criticality": "prod", \
        #         "_change_tag_networking": "on", "attr_tag_networking": "lan", "services" : "Save & Finish", "folder": self.floder, "mode": "newhost" }
        #
        # params = urllib.urlencode(para)
        # ret = urllib.urlopen(uri, params)
        # code = ret.getcode()
        # ret_data = ret.read()
        # print(ret_data)

        return ret[1]

    def DeleteMachine(self):
        print("info: tomcat delete machine")
        url = "http://%s:%s/check_mk/wato.py?mode=folder&_username=icinga_nd&_secret=1234567890&_delete_host=%s&_transid=-1&folder=%s&filled_in=confirm&_do_confirm=Yes!"%(REAL_ICINGA_SERVER.get(self.key), REAL_ICINGA_SERVER_PORT.get(self.key), self.hostName, self.floder)
        print(url)
        ret = GetHttpRequest(url)

        return ret[1]

    def GetKey(self):
        return self.key







PLUGINS["Tomcat"] = "TomcatMonitors"
# json.loads( '[{"bar":["baz", null, 1.0, 2]}]')

if __name__ == "__main__":

    # conf = {"hostname": "flexweb_tomcat_1", "ip":"172.24.133.19", "ports": "8087 8088 8089"}
    # conf = {"hostname": "lzd-test-02", "ip":"172.24.133.41", "ports": "8087 8088 8089"}
    conf = {}
    url = "http://172.24.133.114:8080/infrastructure-console/server/get/flexweb-cl-23"
    Data = GetHttpRequest(url)
    print(Data)
    dicData = json.loads(Data[0])
    conf["hostname"] = dicData.get("name")
    conf["ip"] = dicData.get("network").get("ip")[0]
    ports =" "
    portList = []
    for instance in dicData.get("instance"):
        name = instance.get("name")
        port = instance.get("custom").get("port")
        tmp = "{name}:{port} ".format(name = name, port = port)
        portList.append(tmp)
        # ports.join(tmp)
    print(portList)
    # ports.join(portList)
    print("info")
    print(ports.join(portList))
    conf["ports"] = ports.join(portList)
    conf['place'] = "cl"
    conf['env'] = "pro"

    tomcat =  TomcatMonitors(conf)
    tomcat.CreateMonitors()
    tomcat.AddToMonitorSvr()

    # tomcat.CreateMachine()
    # tomcat.AddToMonitorSvr()
    # tomcat.DeleteMachine()
    # tomcat.ReloadConf()
